<script setup>
import {useApi} from "../../composables/useApi.js"
import showTost from '@/components/toast/index.js'
import {storeToRefs} from "pinia"
import {useAppStore} from "../../store/app.js"

const appStore = useAppStore()

const {nationArr, sexArr} = storeToRefs(appStore)
import {reactive, ref} from "vue"

import {getStudentList} from "@/api/student.js";
import {qualityAddModify, standardAddModify, standardDelete} from "@/api/standard.js";
import QualitySecondListHeader from "@/pages/platform/components/qualitySecondListHeader.vue";
import {qualityDelete} from "@/api/quality.js";
import QualitySecondDrawear from "@/pages/platform/components/qualitySecondDrawear.vue";
const route = useRoute()

//基本数据list
const studentInfo = ref({})
let list = ref([])
let page = ref(1)
let limit = ref(20)
let total = ref(0)//总数
const selected = ref([])
// scoreType '德'... scoreMode 1 小组 2个人
let queryFrom = ref({page: 1, limit: 20, student_id: route.query.student_id,  scoreType: '', scoreMode: '', examcourse_id: ''})

const headers = [
  {
    title: "得分类型",
    key: "scoreType",
    width:"240px",
    align: 'start',
  },
  {
    title: "分值",
    width:"240px",
    align: 'start',
    key: "score",
  },
  {
    title: "得分时间",
    width:"240px",
    align: 'start',
    key: "scoreTime",
  },
  {
    title: "评分老师",
    width:"240px",
    align: 'start',
    key: "teacher_name",
  },

  {
    title: "评分方式",
    width:"240px",
    align: 'start',
    key: "scoreMode",
  },
  {
    title: "得分内容",
    width:"240px",
    align: 'start',
    key: "scoreContent",
  },

  {
    title: "操作",
    align: 'end',
    sortable: false,
    key: "options",
  },
]

const examcourse_id = ref(route.query.examcourse_id)
// todo 复制修改列表接口
const getList = async () => {
  const {data} = await useApi('/admin/Api.Quality/index').post({...queryFrom.value,student_id: route.query.student_id,examcourse_id:examcourse_id.value})
  total.value = data.value.data.total
  studentInfo.value = data.value.data.studentInfo
  list.value = data.value.data.data.map(item => {
    return {
      ...item, id: item.quality_id
    }
  })
}

const dialogFlag = ref(false)
// 头部表单回调
const onChange = val => {
  let data = JSON.parse(JSON.stringify(val))
  data.scoreTime = [data.scoreStartTime,data.scoreEndTime]
  queryFrom.value = {...queryFrom.value, ...data}
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete =  (val) => {
  console.log(val)
  let ids = val.data.map(item => item.quality_id).toString()
  qualityDelete({quality_id:ids}).then(res=>{
    showTost("删除成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    isConfirmDialogVisible.value = false
    if (val.type == 'detail') {
      dialogFlag.value = false
    }
    getList()
  })
}
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref('')
const currentOptionData = ref({})

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == 'delete') {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter(item => selectedItems.value.find(val => val == item.id))
    console.log(data)
    currentOptionData.value = {
      data: data,
      type: 'list'
    }
    confirmMsg.value = `确认删除${data.map(item => item.title).toString()}的信息吗?`
    isConfirmDialogVisible.value = true
  } else if (type == 'openSecondPage'){
    router.push( '/platform/times-manage?type=2')
  } else {
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})
const viewDetail = async (item) => {
  console.log(item)
  const {data} = await useApi('/admin/Api.Quality/detail').post({quality_id: item.quality_id})
  console.log(data)
  detailData.value = data.value.data
  dialogFlag.value = true
}
// 添加教师弹窗falg
const addDialogFlag = ref(false)
const refVForm = ref()

// 下载模板
const downLoadTemplate = async () => {
  const {data} = await useApi('/admin/Base/downFile').post({type: 5})
  console.log(data.value)
  if (data.value.status == 200) {
    const link = document.createElement('a');
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();
  }
}
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()
  addDialogFlag.value = false
}


const valid = ref(false)
const form = reactive({
  student_id: route.query.student_id, //学生ID
  examcourse_id:route.query.examcourse_id,
  scoreType: null, //得分类型
  score: null, //分值
  scoreTime: null, //得分时间
  teacher_id: null, //教师ID
  scoreMode: null, //评分方式
  scoreContent: null, //得分内容
  remarks :null,
  gradeTitle:null
})
watch(()=>form.student_id,val=>{
  console.log(val)
  if(val==null){
    form.classTitle = ''
    form.gradeTitle = ''
    return
  }
  let item = studentList.value.find(item=>item.student_id == val)
  form.classTitle = item.classTitle
  form.gradeTitle = item.gradeTitle
})
let totalScore = computed(()=>{
  return Number(form.languageScore)    +  Number(form.mathsScore) + Number(form.englishScore)
})

const confirmAdd = async () => {
  console.log(totalScore.value)
  if (!valid.value) return
  qualityAddModify({...form,examcourse_id:examcourse_id.value,totalScore:totalScore.value}).then(res=>{
    refVForm.value?.reset()
    addDialogFlag.value = false
    showTost("新增成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    getList()
  })

}
let sexList = ref(['男', '女'])
const onHandleEdit = () => {
  queryFrom.value.page = 1
  getList()
}
// getList()
const required = (value, name) => !!value || `${name}为必填字段`;

const import_page = ref(1)
const import_limit = ref(10)
const import_percent = ref(0)
const loading = ref(false)

const partPost = async (tableData) => {
  let perdata = []
  for (let i = (import_page.value - 1) * import_limit.value; i < import_page.value * import_limit.value; i++) {
    if (tableData[i]) {
      perdata.push(tableData[i])
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value)
  import_percent.value = Math.ceil(import_page.value * 100 / total_page)
  loading.value = true
  console.log(perdata)
  const {data} = await useApi('/admin/Api.Standardization/upload').post(JSON.stringify(perdata))
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1
      partPost(data)
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", {duration: 3000, type: "success"})
      loading.value = false
    }
  }
}

const onChangePage = (val) => {
  queryFrom.value.page = val.page
  queryFrom.value.limit = val.limit
  getList()
}
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data: [val],
    type: 'detail'
  }
  confirmMsg.value = `确认删除该条数据吗`
  isConfirmDialogVisible.value = true
}
const viewDetailClassStudent = (type, item)=>{
  showTost('暂未开放')
  if(type =='class'){

  }
}
// 二级页面显示开关
const secondPageShowFlag = ref(false)
const onHandleSecondPage = ()=>{
  secondPageShowFlag.value = true
}
const changeId = (val)=>{
  examcourse_id.value = val
  getList()
}

const onlyAllowNumbers = (event) => {
  const key = event.key;
  // 检查按键是否为数字或控制键（如 backspace）
  if (!/^\d$/.test(key) && event.key !== 'Backspace' && event.key !== 'Tab') {
    event.preventDefault();
  }
}
const filterInput =(key) => {
  // 仅保留数字
  form[key] = form[key].replace(/\D/g, '');
}

/**  获取学生列表*/
const studentList = ref([])
const getStudentListProp = async () => {
  getStudentList({page:1,limit:999}).then(res=>{
    studentList.value = res.data.value.data
    console.log(studentList.value)
  })
}
getStudentListProp()

// 得分项目列表
const scoreTypeList = ['德', '智', '体', '美','劳']

const scoreModeList = [{
  label: '小组',
  value: 1
}, {
  label: '个人',
  value: 2
}]
// 获取老师列表
const teacherList = ref([])
const getTeacherList = async () => {
  const {data} = await useApi('/admin/Api.Teacher/indexList').post({})
  if (data.value.status == 200) {
    teacherList.value = data.value.data
  }
}
getTeacherList()
</script>

<template>
  <div class="content">
    <!--   Ought to 修改右侧抽屉-->
    <quality-second-drawear @onHandleDelete="drawaerDelete"  @onHandleEdit="onHandleEdit"
                            :detailData="detailData" @update:isDrawerOpen="dialogFlag=$event"
                            :is-drawer-open="dialogFlag" :teacher-list="teacherList" :scoreTypeList="scoreTypeList" :scoreModeList="scoreModeList"></quality-second-drawear>

    <ConfirmDialog
      :handleData="currentOptionData"
      v-model:isDialogVisible="isConfirmDialogVisible"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!--    Ought to 修改顶部检索栏部分-->
    <!-- 头部 -->
    <quality-second-list-header :title="route.query.name+'得分记录-'+route.query.title"
                                button-text="添加信息"
                                :teacher-list="teacherList" :scoreTypeList="scoreTypeList" :scoreModeList="scoreModeList"
                    @onChange="onChange"
                    @changeId="changeId"
                    @onHandle="onHandleDialog"/>
    <VDivider/>

    <div class="student-box">
        <img class="avatar-box" src="../../assets/avatar.png" alt="">
        <div class="student-detail">
          <div class="name">{{studentInfo.real_name}}</div>
          <div class="bottom-detail">
              <div>
                性别：{{studentInfo.sex}}
              </div>
              <div>
                所属：{{studentInfo.gradeTitle}}{{studentInfo.classTitle}}
              </div>
              <div>
                出生：{{studentInfo.brith_time}}
              </div>
          </div>
        </div>
        <div class="right-disciplines">
          <div class="disciplines-item">
            <div class="disciplines-title">德</div>
            <div class="score-box"><span class="num">{{studentInfo.de||0}}</span>分</div>
          </div>
          <div class="disciplines-item">
            <div class="disciplines-title">智</div>
            <div class="score-box"><span class="num">{{studentInfo.zhi||0}}</span>分</div>
          </div>
          <div class="disciplines-item">
            <div class="disciplines-title">体</div>
            <div class="score-box"><span class="num">{{studentInfo.ti||0}}</span>分</div>
          </div>
          <div class="disciplines-item">
            <div class="disciplines-title">美</div>
            <div class="score-box"><span class="num">{{studentInfo.mei||0}}</span>分</div>
          </div>
          <div class="disciplines-item">
            <div class="disciplines-title">劳</div>
            <div class="score-box"><span class="num">{{studentInfo.lao ||0}}</span>分</div>
          </div>
        </div>
    </div>
    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />
    <!--    添加对话框-->
    <VDialog
      :persistent="true"
      max-width="600"
      :model-value="addDialogFlag"
    >
     <div class="dialog-body" style="width: 600px">
       <AppDrawerHeaderSection
         title="添加记录"
         @cancel="addDialogFlag=false"
       />
       <VDivider/>
       <VCard>
         <PerfectScrollbar
           :options="{ wheelPropagation: false }"
           class="h-60"
         >
           <VCardText>
             <VForm
               v-model="valid"
               ref="refVForm"
               @submit.prevent="confirmAdd"
             >
               <VRow>
                 <VCol cols="6">
                   <VSelect
                     v-model="form.scoreType"
                     :items="scoreTypeList"
                     item-title="item"
                     item-value="item"
                     :rules="[(val)=>required(val,'得分类型')]"
                     class="input-width-height"
                   >
                     <template v-slot:label>
                       <span>得分类型</span>
                       <span  style="color: red;margin-left: 4px;">*</span>
                     </template>
                   </VSelect>

                 </VCol>
                 <VCol cols="6">
                   <VTextField
                     v-model="form.score"
                     label="分值"
                     @keypress="onlyAllowNumbers"
                     @input="()=>filterInput('score')"
                     :rules="[(val)=>required(val,'分值')]"
                     placeholder="请输入分值"
                   >
                     <template v-slot:label>
                       <span>分值</span>
                       <span  style="color: red;margin-left: 4px;">*</span>
                     </template>
                   </VTextField>
                 </VCol>
                 <VCol cols="6">
                   <AppDateTimePicker
                     class="input-width-height"
                     v-model="form.scoreTime"
                     label="评分时间"
                     placeholder="请选择评分时间"
                     :rules="[(val)=>required(val,'评分时间')]"
                   >
                     <template v-slot:label>
                       <span>评分时间</span>
                       <span  style="color: red;margin-left: 4px;">*</span>
                     </template>
                   </AppDateTimePicker>
                 </VCol>
                 <VCol cols="6">
                   <VSelect
                     v-model="form.teacher_id"
                     :items="teacherList"
                     item-title="real_name"
                     item-value="teacher_id"
                     placeholder="请选择评分老师"
                     label="评分老师"
                     :rules="[(val)=>required(val,'评分老师')]"
                     class="input-width-height"
                   >
                     <template v-slot:label>
                       <span>评分老师</span>
                       <span  style="color: red;margin-left: 4px;">*</span>
                     </template>
                   </VSelect>
                 </VCol>
                 <VCol cols="6">
                   <VSelect
                     v-model="form.scoreMode"
                     :items="scoreModeList"
                     item-title="label"
                     item-value="value"
                     placeholder="请选择评分方式"
                     label="评分方式"
                     :rules="[(val)=>required(val,'评分方式')]"
                     class="input-width-height"
                   >
                     <template v-slot:label>
                       <span>评分方式</span>
                       <span  style="color: red;margin-left: 4px;">*</span>
                     </template>
                   </VSelect>
                 </VCol>
                 <VCol cols="6">
                   <VTextField
                     v-model="form.scoreContent"
                     label="得分内容"
                     :rules="[(val)=>required(val,'得分内容')]"
                     placeholder="请输入得分内容"
                   >
                     <template v-slot:label>
                       <span>得分内容</span>
                       <span  style="color: red;margin-left: 4px;">*</span>
                     </template>
                   </VTextField>
                 </VCol>
                 <VCol cols="12">
                   <VTextarea
                     type="textarea"
                     v-model="form.remarks"
                     label="评语"
                     :rules="[(val)=>required(val,'评语')]"
                     placeholder="请输入评语"
                   >
                     <template v-slot:label>
                       <span>评语</span>
                       <span  style="color: red;margin-left: 4px;">*</span>
                     </template>
                   </VTextarea>
                 </VCol>
                 <VDivider/>
                 <VCol cols="12">
                   <div class="d-flex justify-end">
                     <VBtn
                       color="#fff"
                       class="me-4"
                       @click="resetForm"
                     >
                       取消
                     </VBtn>
                     <VBtn
                       type="submit"
                       color="primary"
                       class="me-4"
                     >
                       添加
                     </VBtn>
                   </div>
                 </VCol>
               </VRow>
             </VForm>
           </VCardText>
         </PerfectScrollbar>
       </VCard>
     </div>
    </VDialog>
  </div>
</template>

<style lang="scss" scoped>
  .student-box{
    padding: 32px 24px;
    display: flex;
    align-items: center;
    background-color:rgba(var(--v-theme-surface));
    .avatar-box{
      width: 120px;
      height:120px;
      border-radius: 6px;
      margin-right: 24px;
    }
    .student-detail{
      margin-right: 80px;
      .name{
        font-size: 24px;
        color: #433C50;
        margin-bottom: 16px;
      }
      .bottom-detail{
        color: rgba(140, 135, 152, 1);
        font-size: 16px;
        margin-bottom: 5px;
      }

    }
    .right-disciplines{
      display: flex;
      align-items: center;
      flex: 1;
      justify-content: space-between;
      .disciplines-item{
        .disciplines-title{
          font-size: 20px;
          color: rgba(46, 38, 61, 0.9);
        }
        .score-box{
          .num{
            font-size: 40px;
          }
        }
      }
    }
  }
</style>
